package com.snmp.smn.manager;

import java.io.File;
import java.net.Socket;

import org.apache.commons.io.FileUtils;

import com.snmp.smn.beans.Agent;
import com.snmp.smn.db.DBHelper;
import com.snmp.smn.pdu.PDUFactory;
import com.snmp.smn.utils.EmailSender;
import com.snmp.smn.utils.Utilities;

public class MessageProcessor extends Thread {
	
	private Socket socket;

	public MessageProcessor(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		try {
			byte[] b = new byte[1024];
			socket.getInputStream().read(b);
			String message = new String(b).trim();
			
			Utilities.log("Processing message : " + message);
			
			if(message.length() > 2 && Utilities.isCorrectVersion(message)) {
				if (Utilities.isTrapMessage(message)) {
					if (Utilities.isImproperShutdown(message)) {
						String IP = socket.getInetAddress().getHostAddress();
						notifyImproperShutdown(IP);
					}
				} else if (Utilities.isGetRequest(message)) {
					if (Utilities.isGetFileInfo(message)) {
						sendFileInfo(message);
					} else if (Utilities.isGetFileContent(message)) {
						sendFileContent(message);
					}
				}
			}
			
			Utilities.log("Processed message : " + message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void notifyImproperShutdown(String IP) throws Exception {
		Agent agent = DBHelper.getAgentByIP(IP);
		
		if(agent == null) {
			Utilities.log("Ignoring message received from unknown agent " + IP);
		} else {
			EmailSender.sendISNotification(agent.getAgentId(), agent.getAgentName(), 
					agent.getAgentIP(), agent.getAgentPort());
		}
	}
	
	private void sendFileContent(String message) throws Exception {
		String fileName = Utilities.getFileName(message);
		File file = new File(fileName);
		if (file.exists()) {
			Utilities.log("Sending file content for " + fileName);
			
			int index = Utilities.getIndex(message);
			byte[] b = FileUtils.readFileToByteArray(file);
			b = PDUFactory.createFileContentResponsePDU(b[index]);
			socket.getOutputStream().write(b);
		} else {
			Utilities.log("Cannot send file content. Cannot find file " + fileName);
			
			byte[] b = PDUFactory.createFileInfoErrorResponsePDU();
			socket.getOutputStream().write(b);
		}
	}

	private void sendFileInfo(String message) throws Exception {
		String fileName = Utilities.getFileName(message);
		File file = new File(fileName);
		if (file.exists()) {
			Utilities.log("Sending file info for " + fileName);
			
			byte[] b = FileUtils.readFileToByteArray(file);
			b = PDUFactory.createFileInfoResponsePDU(b.length);
			socket.getOutputStream().write(b);
		} else {
			Utilities.log("Cannot send file info. Cannot find file " + fileName);
			
			byte[] b = PDUFactory.createFileInfoErrorResponsePDU();
			socket.getOutputStream().write(b);
		}
	}
	
}
